<template>
	<view class="doctor-list">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input">
				<view class="search-input-box">
					<view class="search-icon-wrap">
						<image class="search-icon" src="/static/icons/search.png" mode="aspectFit"></image>
					</view>
					<input
						type="text"
						v-model="searchKeyword"
						placeholder="搜索医生姓名"
						placeholder-class="placeholder"
						@input="onSearchInput"
						confirm-type="search"
						@confirm="onSearchConfirm"
					/>
					<view v-if="searchKeyword" class="clear-icon" @tap="clearSearch">
						<text class="clear-text">✕</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 筛选条件 -->
		<view class="filter-bar">
			<picker :range="genderOptions" @change="onGenderChange">
				<view class="filter-item">
					<text>{{gender || '性别'}}</text>
					<u-icon name="arrow-down" size="14"></u-icon>
				</view>
			</picker>
			
			<picker :range="positionOptions" @change="onPositionChange">
				<view class="filter-item">
					<text>{{title || '职务'}}</text>
					<u-icon name="arrow-down" size="14"></u-icon>
				</view>
			</picker>
		</view>
		
		<!-- 医生列表 -->
		<scroll-view scroll-y class="doctor-scroll">
			<view v-if="doctorList.length === 0" class="empty-state">
				<text>暂无医生信息</text>
			</view>
			<view v-else class="doctor-item" v-for="(item, index) in doctorList" :key="item.id" @click="goToDetail(item)">
				<image class="doctor-image" :src="item.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
				<view class="doctor-info">
					<view class="doctor-name">{{item.name}}</view>
					<view class="doctor-position">{{item.department}}</view>
					<view class="doctor-tags">
						<text class="tag">{{item.gender}}</text>
						<text class="tag">{{item.position}}</text>
					</view>
					<view class="doctor-desc" v-if="item.desc">{{item.desc}}</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				hospitalId: '',
				departmentId: '',
				searchKeyword: '',
				selectedGender: '',
				selectedPosition: '',
				gender: '',
				title: '',
				// 性别选项
				genderOptions: ['全部', '男', '女'],
				// 性别映射
				genderMap: {
					'男': 1,
					'女': 2
				},
				// 职务选项
				positionOptions: ['全部', '主任', '副主任', '医师'],
				// 原始医生列表数据
				originalDoctorList: [],
				// 显示的医生列表
				doctorList: [],
				// 科室信息缓存
				departmentMap: {}
			}
		},
		onLoad(options) {
			console.log('医生列表页面接收到的参数:', options);
			
			// 获取传入的医院ID和科室ID
			if (options.hospitalId) {
				this.hospitalId = options.hospitalId;
				// 如果有科室ID，说明是从科室列表进入
				if (options.departmentId) {
					this.departmentId = options.departmentId;
				}
				this.getDoctorList();
			} else {
				uni.showToast({
					title: '缺少医院信息',
					icon: 'none'
				});
			}
		},
		methods: {
			clearSearch() {
				this.searchKeyword = '';
				this.filterDoctors();
			},
			
			onSearchInput(e) {
				const value = e.detail.value;
				this.searchKeyword = value;
				this.filterDoctors();
			},
			
			onSearchConfirm(e) {
				const value = e.detail.value;
				this.filterDoctors();
			},
			
			// 性别选择变更
			onGenderChange(e) {
				const index = e.detail.value;
				const selectedValue = this.genderOptions[index];
				this.selectedGender = selectedValue === '全部' ? '' : selectedValue;
				this.gender = this.selectedGender;
				this.filterDoctors();
			},
			
			// 职务选择变更
			onPositionChange(e) {
				const index = e.detail.value;
				const selectedValue = this.positionOptions[index];
				this.selectedPosition = selectedValue === '全部' ? '' : selectedValue;
				this.title = this.selectedPosition;
				this.filterDoctors();
			},
			
			// 获取科室信息
			async getDepartmentInfo(departmentId) {
				return new Promise((resolve) => {
					// 如果已经有缓存的科室信息，直接返回
					if (this.departmentMap[departmentId]) {
						resolve(this.departmentMap[departmentId]);
						return;
					}
					
					// 请求科室信息
					uni.request({
						url: `http://localhost:8090/dep/${departmentId}`,
						method: 'GET',
						success: (res) => {
							console.log('获取科室信息响应:', res);
							if (res.statusCode === 200 && res.data.code === 200) {
								const depInfo = res.data.data;
								if (depInfo && depInfo.name) {
									// 缓存科室信息
									this.departmentMap[departmentId] = depInfo.name;
									resolve(depInfo.name);
								} else {
									resolve('暂无科室信息');
								}
							} else {
								resolve('暂无科室信息');
							}
						},
						fail: () => {
							resolve('暂无科室信息');
						}
					});
				});
			},
			
			// 更新医生列表的科室信息
			async updateDoctorsWithDepartment(doctors) {
				const updatedDoctors = [];
				for (const doctor of doctors) {
					if (doctor.departmentId) {
						const departmentName = await this.getDepartmentInfo(doctor.departmentId);
						updatedDoctors.push({
							...doctor,
							department: departmentName
						});
					} else {
						updatedDoctors.push({
							...doctor,
							department: '暂无科室信息'
						});
					}
				}
				return updatedDoctors;
			},
			
			// 筛选医生
			filterDoctors() {
				// 构建查询参数
				const queryPageBean = {
					currentPage: 1,
					pageSize: 10,
					hospitalId: this.hospitalId,
					departmentId: this.departmentId,
					queryString: this.searchKeyword ? this.searchKeyword.trim() : '',
					gender: this.selectedGender && this.selectedGender !== '全部' ? this.genderMap[this.selectedGender] : null,
					title: this.selectedPosition && this.selectedPosition !== '全部' ? this.selectedPosition : null
				};
				
				console.log('发送筛选请求，参数:', JSON.stringify(queryPageBean));
				
				// 根据是否有科室ID选择不同的接口
				const url = this.departmentId 
					? 'http://localhost:8090/dep/findDocByDepId'
					: 'http://localhost:8090/hospital/findDocByHospitalId';
				
				uni.request({
					url: url,
					method: 'POST',
					data: queryPageBean,
					header: {
						'Content-Type': 'application/json'
					},
					success: async (res) => {
						console.log('获取医生列表响应:', res);
						if (res.statusCode === 200) {
							const data = res.data;
							if (data && Array.isArray(data.rows)) {
								const doctors = data.rows.map(doctor => ({
									id: doctor.id,
									name: doctor.name,
									avatar: doctor.imgurl || '/static/default-avatar.png',
									position: doctor.title || '暂无职务',
									departmentId: doctor.departmentId,
									gender: doctor.gender === 1 ? '男' : '女',
									desc: doctor.desc
								}));
								
								// 更新医生列表的科室信息
								const updatedDoctors = await this.updateDoctorsWithDepartment(doctors);
								this.doctorList = updatedDoctors;
								this.originalDoctorList = [...updatedDoctors];
								
								if (doctors.length === 0) {
									uni.showToast({
										title: '暂无符合条件的医生',
										icon: 'none'
									});
								}
							} else {
								this.doctorList = [];
								this.originalDoctorList = [];
								uni.showToast({
									title: '暂无医生信息',
									icon: 'none'
								});
							}
						} else {
							this.doctorList = [];
							this.originalDoctorList = [];
							uni.showToast({
								title: data?.msg || '获取医生列表失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('请求失败:', err);
						this.doctorList = [];
						this.originalDoctorList = [];
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 获取医生列表
			getDoctorList() {
				const queryPageBean = {
					currentPage: 1,
					pageSize: 10,
					hospitalId: this.hospitalId,
					departmentId: this.departmentId
				};
				
				console.log('发送初始请求，参数:', JSON.stringify(queryPageBean));
				
				// 根据是否有科室ID选择不同的接口
				const url = this.departmentId 
					? 'http://localhost:8090/dep/findDocByDepId'
					: 'http://localhost:8090/hospital/findDocByHospitalId';
				
				uni.request({
					url: url,
					method: 'POST',
					data: queryPageBean,
					header: {
						'Content-Type': 'application/json'
					},
					success: async (res) => {
						console.log('获取医生列表响应:', res);
						if (res.statusCode === 200) {
							const data = res.data;
							if (data && Array.isArray(data.rows)) {
								const doctors = data.rows.map(doctor => ({
									id: doctor.id,
									name: doctor.name,
									avatar: doctor.imgurl || '/static/default-avatar.png',
									position: doctor.title || '暂无职务',
									departmentId: doctor.departmentId,
									gender: doctor.gender === 1 ? '男' : '女',
									desc: doctor.desc
								}));
								
								// 更新医生列表的科室信息
								const updatedDoctors = await this.updateDoctorsWithDepartment(doctors);
								this.doctorList = updatedDoctors;
								this.originalDoctorList = [...updatedDoctors];
								
								if (doctors.length === 0) {
									uni.showToast({
										title: '暂无医生信息',
										icon: 'none'
									});
								}
							} else {
								this.doctorList = [];
								this.originalDoctorList = [];
								uni.showToast({
									title: '暂无医生信息',
									icon: 'none'
								});
							}
						} else {
							this.doctorList = [];
							this.originalDoctorList = [];
							uni.showToast({
								title: data?.msg || '获取医生列表失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('请求失败:', err);
						this.doctorList = [];
						this.originalDoctorList = [];
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 跳转到医生详情页
			goToDetail(doctor) {
				uni.navigateTo({
					url: `/pages/doctor/docList?id=${doctor.id}&department=${encodeURIComponent(doctor.department)}`,
					fail: (err) => {
						console.error('跳转失败:', err);
						uni.showToast({
							title: '页面跳转失败',
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.doctor-list {
	min-height: 100vh;
	background-color: #f5f5f5;
	
	.search-bar {
		background: linear-gradient(135deg, #4CD964, #39b54a);
		padding: 16rpx 30rpx;
		position: sticky;
		top: 0;
		z-index: 100;
		
		.search-input {
			background-color: rgba(255, 255, 255, 0.98);
			border-radius: 32rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;
			
			&:hover {
				box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.15);
			}
			
			.search-input-box {
				display: flex;
				align-items: center;
				padding: 8rpx 20rpx;
				
				.search-icon-wrap {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 36rpx;
					height: 36rpx;
					margin-right: 12rpx;
					
					.search-icon {
						width: 28rpx;
						height: 28rpx;
						opacity: 0.7;
					}
				}
				
				input {
					flex: 1;
					height: 52rpx;
					font-size: 26rpx;
					color: #333;
					padding: 0 8rpx;
				}
				
				.placeholder {
					color: #bbb;
					font-size: 26rpx;
				}
				
				.clear-icon {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 36rpx;
					height: 36rpx;
					border-radius: 50%;
					background-color: #f5f5f5;
					margin-left: 12rpx;
					transition: all 0.2s ease;
					
					.clear-text {
						color: #999;
						font-size: 22rpx;
						line-height: 1;
					}
					
					&:active {
						background-color: #e0e0e0;
						transform: scale(0.95);
					}
				}
			}
		}
	}
	
	.filter-bar {
		display: flex;
		background-color: #fff;
		padding: 0;
		margin: 0;
		border-radius: 0;
		width: 100%;
		
		picker {
			flex: 1;
		}
		
		.filter-item {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 44px;
			font-size: 14px;
			color: #333;
			
			text {
				margin-right: 4px;
			}
			
			.u-icon {
				color: #666;
				font-size: 12px;
			}
		}
	}
	
	.doctor-scroll {
		height: calc(100vh - 100px);
	}
	
	.doctor-item {
		display: flex;
		padding: 15px;
		background-color: #fff;
		margin-bottom: 10px;
		
		.doctor-image {
			width: 80px;
			height: 80px;
			border-radius: 50%;
			margin-right: 12px;
		}
		
		.doctor-info {
			flex: 1;
			
			.doctor-name {
				font-size: 16px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
			}
			
			.doctor-position {
				font-size: 14px;
				color: #666;
				margin-bottom: 4px;
			}
			
			.doctor-department {
				font-size: 14px;
				color: #666;
				margin-bottom: 6px;
			}
			
			.doctor-tags {
				margin-top: 8rpx;
				
				.tag {
					display: inline-block;
					padding: 4rpx 12rpx;
					background-color: #f0f9eb;
					color: #67c23a;
					font-size: 24rpx;
					border-radius: 4rpx;
					margin-right: 12rpx;
					margin-bottom: 8rpx;
				}
			}
			
			.doctor-desc {
				font-size: 24rpx;
				color: #666;
				margin-top: 8rpx;
				line-height: 1.4;
			}
		}
	}
	
	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200rpx;
		color: #999;
		font-size: 28rpx;
	}
}
</style>
